package cn.itcast.action;

import cn.itcast.crm.domain.Customer;
import cn.itcast.utils.MailUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/7/19/019.
 */
@ParentPackage("struts-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{


    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Action(value="customer_sendSms")
    public String sendSms(){
        final String randomCode = RandomStringUtils.randomNumeric(4);
        ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),randomCode);
        System.out.println("验证码:"+randomCode);
        //destinationName必须和消费者监听器一致
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone",model.getTelephone());
                mapMessage.setString("checkCode",randomCode);
                return mapMessage;
            }
        });

        return NONE;
    }

    //模型驱动
    private String checkCode;

    public void setCheckCode(String checkCode) {
        this.checkCode = checkCode;
    }

    @Action(value = "customer_regist",results = {
            @Result(name = "success",type = "redirect",location = "signup-success.html"),
            @Result(name = "input",type = "redirect",location = "signup.html")
    })
    public String regist(){
        String checkCodeSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
        System.out.println("checkCodeSession"+checkCodeSession);
        if (checkCodeSession==null||!checkCodeSession.equals(checkCode)){
            System.out.println("验证码错误");
            return INPUT;
        }
        //发送激活邮件
        //生成激活码
        final String activecode = RandomStringUtils.randomNumeric(32);
        redisTemplate.opsForValue().set(model.getTelephone(),activecode,24, TimeUnit.HOURS);
        String content = "尊敬的客户你好,请于24小时内,进行邮箱账户的绑定,点击下面地址完成绑定:</br><a href='"
                + MailUtils.getActiveUrl()+"?telephone="+model.getTelephone()
                +"&activecode="+activecode+"'>速运快递邮箱绑定地址</a>";
        System.out.println("激活码为"+activecode);
        MailUtils.run("836185624@qq.com",activecode,content);
        System.out.println(model.toString());
        WebClient.create("http://localhost:8888/crm/service/customerService/customer_register/").accept(MediaType.APPLICATION_JSON).post(model);
        return SUCCESS;
    }

    private String activecode;

    public void setActivecode(String activecode) {
        this.activecode = activecode;
    }

    @Action("customer_activeMail")
    public String activeMail() throws IOException {
        ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
        String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
        //判断激活码是否失效
        if (activecodeRedis==null||!activecodeRedis.equals(activecode)){
            ServletActionContext.getResponse().getWriter().println("激活码无效,请登录系统,重新绑定邮箱");
            return NONE;
        }
        //获取客户绑定邮箱状态
       Customer curCustomer = WebClient.create("http://localhost:8888/crm/service/customerService/customer_telephone/" +
               model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);

        System.out.println(curCustomer.toString());

        //如果没有绑定邮箱

        if(curCustomer.getType()==null||curCustomer.getType()!=1){
            WebClient.create("http://localhost:8888/crm/service/customerService/updateType/"+curCustomer.getTelephone()).get();
            ServletActionContext.getResponse().getWriter().println("邮箱绑定成功!");
        }else{
            ServletActionContext.getResponse().getWriter().println("邮箱已经绑定,无需重复绑定");
        }
        redisTemplate.delete(model.getTelephone());
        return NONE;
    }
}
